<template>
  <div>
    <div class="nav">
      <div class="city">{{ city }}</div>

      <!-- 城市搜索 -->
      <div class="search-item">
        <div class="search-box">
          <i class="iconfont icon-sousuo"></i>
          <input
            type="text"
            v-model="chosenCity"
            placeholder="请搜索你所在的城市"
            @keyup.enter="searchCity"
          />
        </div>
      </div>

      <!-- 绘制类型选择 -->
      <div class="search-item">
        <select v-model="selectedType" id="selectType">
          <option value="" disabled selected>选择绘制类型</option>
          <option value="LineString">绘制线</option>
          <option value="Polygon">绘制面</option>
          <option value="Circle">绘制圆</option>
          <option value="delete">清空</option>
        </select>
      </div>

      <!-- 矢量图标选择 -->
      <div class="search-item">
        <select v-model="selectedFeature" id="selectFeature">
          <option value="" disabled selected>选择绘制的矢量图标</option>
          <option value="便利店">便利店</option>
          <option value="加油站">加油站</option>
          <option value="酒店">酒店</option>
          <option value="delete">清空图标</option>
        </select>
      </div>
    </div>
    <div ref="overlayElement" class="overlay"></div>
    <div id="map"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Draw from 'ol/interaction/Draw';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Icon from 'ol/style/Icon'; // 添加这行导入

import Overlay from 'ol/Overlay'; // 确保导入 Overlay

// 添加以下导入
import Cluster from 'ol/source/Cluster';
import Circle from 'ol/style/Circle';
import Text from 'ol/style/Text';

// 定义原始源和聚合源
let originalSource;
let clusterSource;

const GAODEKEY = '6806a666fdfcd4bb5cac88647eb9dc34';

let city = ref('武汉市');
let adcode = ref();
let chosenCity = ref('');
let map;
let cityLayer2;
// 添加状态控制变量
const isDrawingMode = ref(false);
const isAddingPoint = ref(false);

const overlayElement = ref(null);
let view = new View({
  projection: 'EPSG:4326',
  center: [114.305449, 30.593099],
  zoom: 4,
});
let gaodeLayer = new TileLayer({
  source: new XYZ({
    url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
  }),
});
//添加底图跟矢量图层
let cityLayer;
let vectorLayer;
let vectorLayer2;

onMounted(() => {
  map = new Map({
    view,
    target: 'map',
    layers: [gaodeLayer],
  });
  setTimeout(async () => {
    //根据当前的位置发送请求定位
    const temp = await fetch('https://restapi.amap.com/v3/ip?key=' + GAODEKEY);
    let data = await temp.json();
    city.value = data.city;
    adcode.value = data.adcode;
    //根据Adcode发请求得到所在城市的矢量数据
    cityLayer = new VectorLayer({
      source: new VectorSource({
        url: `https://geo.datav.aliyun.com/areas_v3/bound/${adcode.value}.json`,
        format: new GeoJSON(),
      }),
      style: new Style({
        fill: new Fill({
          color: 'rgba(255,0,0, 0.5)',
        }),
        stroke: new Stroke({
          color: 'black',
          width: 2,
        }),
      }),
    });
    map.addLayer(cityLayer);
    view.animate({
      zoom: 8,
      duration: 2000,
    });
  }, 1000);
  //定义一个矢量图层 用来放置draw绘制的要素
  vectorLayer = new VectorLayer({
    source: new VectorSource(),
    style: new Style({
      stroke: new Stroke({
        color: 'red',
        width: 2,
      }),
      fill: new Fill({
        color: 'pink',
      }),
    }),
  });
  map.addLayer(vectorLayer);

  cityLayer2 = new VectorLayer({
    source: new VectorSource({
      url: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full_city.json',
      format: new GeoJSON(),
    }),
  });
  map.addLayer(cityLayer2);

  const overlay = new Overlay({
    element: overlayElement.value, // 使用ref引用
    positioning: 'bottom-center',
    autoPan: true,
    offset: [0, -10],
  });
  map.addOverlay(overlay);
  map.on('click', function (e) {
    if (isDrawingMode.value || isAddingPoint.value) return;
    // 同时查询所有可能包含数据的图层
    const features = map.getFeaturesAtPixel(e.pixel) || [];

    if (features.length > 0) {
      const f = features[0];
      const props = {
        name: f.get('name'),
        adcode: f.get('adcode'),
        level: f.get('level'),
      };

      overlay.getElement().innerHTML = `
      <div>
        <p>名称：${props.name}</p>
        <p>编码：${props.adcode}</p>
        <p>级别：${props.level}</p>
      </div>
    `;
      overlay.setPosition(e.coordinate); // 使用点击坐标而非要素中心
      setTimeout(() => {
        overlay.setPosition(undefined);
      }, 2000);
    } else {
      overlay.setPosition(undefined);
    }
  });

  // 创建矢量图层（修改部分）
  originalSource = new VectorSource();
  clusterSource = new Cluster({
    distance: 40,
    source: originalSource,
  });
  vectorLayer2 = new VectorLayer({
    source: clusterSource,
    style: function (feature) {
      const size = feature.get('features').length;
      if (size > 1) {
        return new Style({
          image: new Circle({
            radius: 15,
            fill: new Fill({ color: 'rgba(255, 100, 100, 0.8)' }),
            stroke: new Stroke({ color: 'white', width: 2 }),
          }),
          text: new Text({
            text: size.toString(),
            fill: new Fill({ color: 'white' }),
          }),
        });
      } else {
        const features = feature.get('features');
        return features[0]?.getStyle();
      }
    },
  });
  map.addLayer(vectorLayer2);
});
async function searchCity() {
  const temp = await fetch(
    `https://restapi.amap.com/v3/geocode/geo?address=${chosenCity.value}&key=${GAODEKEY}`
  );
  let data = await temp.json();
  if (data.status === '0') {
    alert('未找到该城市');
  }
  city.value = data.geocodes[0].city;
  adcode.value = data.geocodes[0].adcode;
  let center = data.geocodes[0].location.split(',').map(Number);
  let citySource = cityLayer.getSource();
  citySource.clear();
  cityLayer = new VectorLayer({
    source: new VectorSource({
      url: `https://geo.datav.aliyun.com/areas_v3/bound/${adcode.value}.json`,
      format: new GeoJSON(),
    }),
    style: new Style({
      fill: new Fill({
        color: 'rgba(255,0,0, 0.5)',
      }),
      stroke: new Stroke({
        color: 'black',
        width: 2,
      }),
    }),
  });
  map.addLayer(cityLayer);
  view.animate({
    center,
    duration: 2000,
  });
}

// 第二个框架效果实现：绘制类型选择
const selectedType = ref('');
let draw;
watch(selectedType, (newValue) => {
  if (newValue === 'delete') {
    vectorLayer.getSource().clear();
    map.removeInteraction(draw);
    selectedType.value = '';
  } else if (newValue) {
    isDrawingMode.value = true; // 进入绘制模式
    isAddingPoint.value = false;
    map.removeInteraction(draw);
    draw = new Draw({
      type: newValue,
      source: vectorLayer.getSource(),
    });
    map.addInteraction(draw);
  }
});

// 第三个框架效果实现：矢量图标选择
const selectedFeature = ref('');
// 定义点击事件处理函数
// 修改点击添加点的处理函数
const handleMapClick = (e) => {
  const currentZoom = view.getZoom();
  if (currentZoom <= 13) {
    alert('请放大到13级以上缩放级别以添加点');
    return;
  }
  const point = new Feature({
    geometry: new Point(e.coordinate),
  });
  point.setStyle(
    new Style({
      image: new Icon({
        src: `public/${selectedFeature.value}.svg`,
        scale: 0.5,
        anchor: [0.5, 1],
      }),
    })
  );
  originalSource.addFeature(point); // 添加到原始源
};

watch(selectedFeature, (newValue1) => {
  if (newValue1 === 'delete') {
    originalSource.clear(); // 修改为清空原始源
    map.un('click', handleMapClick);
    selectedFeature.value = '';
  } else if (newValue1) {
    isAddingPoint.value = true; // 进入添加点模式
    isDrawingMode.value = false;
    map.removeInteraction(draw);
    map.un('click', handleMapClick);
    map.on('click', handleMapClick);
  }
});
</script>

<style lang="scss" scoped>
.nav {
  width: 100%;
  min-height: 60px;
  background: #3454f3;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 50px;
  gap: 30px;

  // 统一搜索/选择容器样式
  .search-item,
  .select-item {
    height: 40px;

    .search-box,
    .select-box {
      background: #f5f7fa;
      border-radius: 8px;
      padding: 0 15px;
      height: 100%;
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #ebedf0;
      }
    }
  }

  // 搜索框特殊样式
  .search-item {
    input {
      border: none;
      background: transparent;
      outline: none;
      font-size: 14px;
      // width: 180px;
    }
  }

  .search-item select {
    height: 40px;
    width: 180px;
  }
}

#map {
  width: 100%;
  height: calc(100vh - 60px);
}

.iconfont {
  font-size: 14px;
  color: #909399;
}

.overlay {
  position: absolute !important;
  /* 必须的定位属性 */
  background: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  min-width: 120px;
  transform: translate(-50%, -100%);
  /* 居中定位 */
  z-index: 1000;

  /* 添加指示箭头 */
  &::after {
    content: '';
    position: absolute;
    left: 50%;
    bottom: -10px;
    transform: translateX(-50%);
    border: 10px solid transparent;
    border-top-color: white;
  }
}
</style>
